package handler

import (
	"context"
	"fmt"
	"math/rand"
	"server/basic/global"
	"server/basic/inits"
	"server/models"
	__ "server/proto"
	"time"
	"unicode"
)

type Server struct {
	__.UnimplementedUserServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) Sendsms(_ context.Context, in *__.SendsmsRequest) (*__.SendsmsResponse, error) {
	code := rand.Intn(9000) + 1000
	inits.RedisClient.Set(context.Background(), "sendsms"+in.Tel+in.Score, code, time.Minute*7)
	return &__.SendsmsResponse{}, nil
}
func IsNum(s string) bool {
	for _, v := range s {
		if !unicode.IsDigit(v) {
			return false
		}
	}
	return true
}
func (s *Server) Login(_ context.Context, in *__.LoginRequest) (*__.LoginResponse, error) {
	if len(in.Tel) != 11 || !IsNum(in.Tel) {
		return nil, fmt.Errorf("请填写正确的电话号码")
	}
	var find models.Users
	global.DB.Where("tel = ?", in.Tel).Find(&find)
	if find.Tel == "" {
		return nil, fmt.Errorf("用户不存在")
	}
	//get := inits.RedisClient.Get(context.Background(), "sendsms"+in.Tel+"login")
	//if get.Val() != in.Sendsms {
	//	return nil, fmt.Errorf("短信验证码错误")
	//}
	//err := inits.RedisClient.Del(context.Background(), "sendsms"+in.Tel+"login").Err()
	//if err != nil {
	//	return nil, fmt.Errorf("短信验证码已过期")
	//}

	return &__.LoginResponse{
		Id: find.Id,
	}, nil
}
func (s *Server) List(_ context.Context, in *__.ListRequest) (*__.ListResponse, error) {
	var find []models.VideoWorks
	global.DB.Find(&find)
	var finds []*__.List
	for _, v := range find {
		list := &__.List{
			Tittle:         v.Title,
			Desc:           v.Desc,
			MusicId:        int64(v.MusicId),
			WorkType:       v.WorkType,
			CheckStatus:    v.CheckStatus,
			IdAddress:      v.IpAddress,
			WorkPermission: v.WorkPermission,
			LikeCount:      int64(v.LikeCount),
			CommentCount:   int64(v.CommentCount),
		}
		finds = append(finds, list)
	}
	return &__.ListResponse{
		List: finds,
	}, nil
}
func (s *Server) Del(_ context.Context, in *__.DelRequest) (*__.DelResponse, error) {
	var find models.VideoWorks
	global.DB.Where("id = ?", in.Id).Find(&find)
	if find.Id == 0 {
		return nil, fmt.Errorf("用户不存在 不能删除")
	}
	del := models.VideoWorks{
		Id: find.Id,
	}
	global.DB.Delete(&del)
	return &__.DelResponse{}, nil
}
